package com.example.newfragment;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import cn.jpush.android.api.JPushInterface;

import com.boyuan.huijiaoyu.MainActivity;
import com.boyuan.huijiaoyu.R;
import com.boyuan.huijiaoyu.SplashActivity;
import com.magicsoft.app.helper.ScreenManager;
import com.magicsoft.app.helper.SharePreferenceHelper;
import com.magicsoft.constant.Constant;
import com.magicsoft.weitown.fragment.HomeNewFragment;
import com.ttcaca.cas.android.client.model.User;

public class JPushReciever extends BroadcastReceiver {

	private static final String TAG = "JPushReciever";

	private Context aContext;

	NotificationManager mNotifMan;

	LocalBroadcastManager mLocalBroadcastManager;

	@Override
	public void onReceive(Context context, Intent intent) {

		aContext = context;
		Bundle bundle = intent.getExtras();
		String message = "";

		if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String registrationID = JPushInterface.getRegistrationID(aContext);
            SharePreferenceHelper.setRegistrationId(registrationID, context);
                        
        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
        	processCustomMessage(context, bundle);
        	message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
        	
        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
            
        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
//        	Intent intent2 = new Intent(context,MainActivity.class);
//        	intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        	context.startActivity(intent2);
        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
        }
		
	}

	// 获取推送通知注册码
	private void getPushRegId(Context ctx) {

		if (mLocalBroadcastManager == null) {
			mLocalBroadcastManager = LocalBroadcastManager.getInstance(ctx);
		}

		Log.e(TAG, "~~~~~~~~~~~~~注册设备ID");

		Intent data1 = new Intent();
		data1.setAction(Constant.ACTION_PUSHMESSAGE_REG);
		mLocalBroadcastManager.sendBroadcast(new Intent(data1));

	}

//	private void sendNotification(Context ctx, Bundle bundle) {
//		User account = SharePreferenceHelper.GetAccount(ctx);
//		int notifysound = 0;
//		if (account != null) {
//			notifysound = SharePreferenceHelper.getIntValue(ctx,
//					account.getUid());
//		}
//
//		if (bundle == null) {
//			return;
//
//		}
//
//		String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
//		String cmd = bundle.getString(JPushInterface.EXTRA_CONTENT_TYPE);
//
//		Log.e(TAG, "Get MSG:" + message + ",CMD" + cmd);
//
//		if (mNotifMan == null) {
//			mNotifMan = (NotificationManager) ctx
//					.getSystemService(Context.NOTIFICATION_SERVICE);
//		}
//		
//		if (mLocalBroadcastManager == null) {
//			mLocalBroadcastManager = LocalBroadcastManager.getInstance(ctx);
//		}
//
//		int icon = R.drawable.ic_launcher1;
//		CharSequence tickerText = message;
//		long when = System.currentTimeMillis();
//
//		Notification notification = new Notification(icon, tickerText, when);
//
//		notification.flags = Notification.FLAG_AUTO_CANCEL;
//		if (notifysound == 0) {
//			notification.defaults = Notification.DEFAULT_ALL;
//		} else {
//			notification.sound = null;
//			notification.vibrate = null;
//		}
//
//		// notification.sound = Uri.parse("android.resource://"
//		// + ctx.getPackageName() + "/" + R.raw.notice);
//		// long[] vibrate = { 0, 100, 200, 300 };
//		// notification.vibrate = vibrate;
//		Log.e("Reviever", "get a message");
//		// PackageManager pm = ctx.getPackageManager();
//		// Intent intent = pm.getLaunchIntentForPackage(ctx.getPackageName());
//		// intent.setAction(Intent.ACTION_MAIN);
//		// intent.addCategory(Intent.CATEGORY_LAUNCHER);
//		// intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//		//
//		// PendingIntent pi = PendingIntent.getActivity(ctx, 0, intent, 0);
//
//		Intent intent;
//		PendingIntent pi;
//		if (ScreenManager.getScreenManager().hasActivity() == true) {
//
//			intent = new Intent(ctx, ctx.getClass());
//			intent.setAction(Intent.ACTION_MAIN);
//			intent.addCategory(Intent.CATEGORY_LAUNCHER);
//			intent.setClass(aContext, SplashActivity.class);
//			intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
//					| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
//			pi = PendingIntent.getActivity(ctx, 0, intent,
//					PendingIntent.FLAG_UPDATE_CURRENT);
//
//		} else {
//
//			PackageManager pm = ctx.getPackageManager();
//			intent = pm.getLaunchIntentForPackage(ctx.getPackageName());
//			intent.setAction(Intent.ACTION_MAIN);
//			intent.setClass(aContext, SplashActivity.class);
//			intent.addCategory(Intent.CATEGORY_LAUNCHER);
//			intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
//					| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
//			pi = PendingIntent.getActivity(ctx, 0, intent, 0);
//		}
//		notification.setLatestEventInfo(ctx,
//				// 卡卡兔通知
//				aContext.getResources().getString(R.string.kakatool_notice),
//				message, pi);
//
//		if (cmd != null && cmd.length() > 0) {
//
//			String command = "";
//			String otherParam = "";
//
//			if (cmd.contains("|")) {
//
//				String[] cmds = cmd.split("\\|");
//				command = cmds[0];
//				if (cmds.length > 1) {
//					otherParam = cmds[1];
//				}
//
//				Log.e(TAG, "c:" + command + ",param:" + otherParam);
//			} else {
//				command = cmd;
//			}
//
//			
//
//		}
//		mNotifMan.notify(message, 1, notification);
//		// mNotifMan.notify(1, notification);
//	}

	// 打印所有的 intent extra 数据
	private static String printBundle(Bundle bundle) {

		if(bundle == null){
			return "";
		}
		StringBuilder sb = new StringBuilder();
		for (String key : bundle.keySet()) {
			if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
				sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
			} else {
				sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
			}
		}
		return sb.toString();
	}

	private void processCustomMessage(Context context, Bundle bundle) {
//		if (HomeNewFragment.isForeground) {
			String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
			String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
//			Log.e(TAG, "processCustomMessage message = " + message);
//			Log.e(TAG, "processCustomMessage extras = " + extras);
			Intent msgIntent = new Intent(HomeNewFragment.MESSAGE_RECEIVED_ACTION);
			msgIntent.putExtra(HomeNewFragment.KEY_MESSAGE, message);
			if (!ExampleUtil.isEmpty(extras)) {
				try {
					JSONObject extraJson = new JSONObject(extras);
					if (null != extraJson && extraJson.length() > 0) {
						msgIntent.putExtra(HomeNewFragment.KEY_EXTRAS, extras);
					}
				} catch (JSONException e) {
					
				}

			}
			context.sendBroadcast(msgIntent);
//		}
	}
	
}
